package com.lotus.minio.controller;

import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.lotus.minio.service.MinioService;

@RestController
public class MinIOController {
	private final MinioService minioService;
	
	// 构造函数注入 MinioService，确保控制器与业务逻辑分离
	public MinIOController(MinioService minioService) {
		this.minioService = minioService;
	}
	
	
	/**
     * 文件上传接口
     * @param file 前端上传的文件
     * @return 上传结果的响应
     */
	@PostMapping("/upload")
	public ResponseEntity<?> uploadFiles(@RequestParam("file") MultipartFile file) {

		// 判断上传文件是否为空
		if (file.isEmpty()) {
			return buildErrorResponse("文件不能为空", 400);
		}

		// 上传文件
		try {
			String url = minioService.uploadFile(file);
			return buildSuccessResponse(Map.of("url", url));
		} catch (Exception e) {
			// TODO: handle exception
			return buildErrorResponse("文件上传失败：" + e.getMessage(), 500);
		}

	}

	/**
     * 构建成功响应
     * @param data 响应数据
     * @return 成功的 ResponseEntity
     */
	private ResponseEntity<?> buildSuccessResponse(Object data) {
		// TODO Auto-generated method stub
		return ResponseEntity.ok(Map.of("success", true, "data", data));
	}

	/**
     * 构建错误响应
     * @param message 错误信息
     * @param status HTTP 状态码
     * @return 错误的 ResponseEntity
     */
	private ResponseEntity<?> buildErrorResponse(String message, int status) {
		// TODO Auto-generated method stub
		return ResponseEntity.status(status).body(Map.of("success", false, "message", message));
	}
	
}
